import 'package:app_core/app_core.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:yh_core_flutter_project/project/common/constant/index.dart';
import 'package:yh_core_flutter_project/project/common/managers/user_manager.dart';
import '../../../common/intl/index.dart';
import 'login_logic.dart';

class LoginPage extends StatelessWidget{
    LoginPage({super.key});

  final logic = Get.put(LoginLogic());

  @override
  Widget build(BuildContext context) {
    return DismissKeyboardWidget(
      child: Scaffold(
        backgroundColor: AppColor.white,
        appBar: MyAppBar(
          '登录',
          showBack: false,
          actions:[ AppButton.text(
            width: 44,
            foregroundColor: Colors.red,
            style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
            text: '测试',
            onTap: logic.navigateToTest,
          )],
        ),
        body: SingleChildScrollView(
          padding: EdgeInsets.symmetric(horizontal: 10),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              _buildLogoSection(),
              SizedBox(height: 48),
              _buildLoginTypeSelector(),
              SizedBox(height: 24),
              _buildAccountInput(),
              SizedBox(height: 24),
              _buildVerificationCodeInput(),
              SizedBox(height: 48),
              _buildPrivacy(),
              SizedBox(height: 32),
              _buildLoginButton(),
              SizedBox(height: 32),
              _buildSignUpSection(),
              SizedBox(height: 40),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildLogoSection() {
    return Padding(
      padding: EdgeInsets.only(top: 20),
      child: Column(
        children: [
          GestureDetector(
            onTap: logic.onLogoTap,
            child: Container(
              width: 80,
              height: 80,
              decoration: const BoxDecoration(shape: BoxShape.circle, color: AppColor.logoBackground),
              child: Obx(
                () =>
                    logic.logoTapCount.value > 0
                        ? Center(child: Text("${logic.logoTapCount.value}", style: AppStyles.s20b.copyWith(color: AppColor.white)))
                        : SpaceBox.shrink,
              ),
            ),
          ),
          const SizedBox(height: 16),
          Text('百卓唯相框', style: AppStyles.s20b.copyWith(color: AppColor.logoBackground)),
        ],
      ),
    );
  }

  Widget _buildLoginTypeSelector() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16),
      child: Container(
        decoration: BoxDecoration(color: AppColor.inputBackground, borderRadius: AppSpaces.borderRadiusMd),
        child: Obx(
          () => Row(
            children: [
              Expanded(child: _buildTypeTab('邮箱登录', logic.isEmailLogin.value, () => logic.switchToEmail())),
              Expanded(child: _buildTypeTab('手机登录', !logic.isEmailLogin.value, () => logic.switchToPhone())),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildTypeTab(String title, bool isActive, VoidCallback onTap) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: EdgeInsets.symmetric(vertical: 12),
        decoration: BoxDecoration(color: isActive ? AppColor.primary : Colors.transparent, borderRadius: AppSpaces.borderRadiusMd),
        child: Text(
          title,
          textAlign: TextAlign.center,
          style: TextStyle(color: isActive ? AppColor.white : AppColor.textSecondary, fontSize: 14, fontWeight: isActive ? FontWeight.w500 : FontWeight.normal),
        ),
      ),
    );
  }

  Widget _buildAccountInput() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16),
      child: Obx(() {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(logic.isEmailLogin.value ? '电子邮箱' : '手机号码', style: TextStyle(color: Get.theme.colorScheme.onSurface, fontSize: 14)),
            SizedBox(height: 8),
            AppTextField.prefixInput(
              focusNode: logic.accountFocusNode,
              keyboardType: logic.isEmailLogin.value ? TextInputType.emailAddress : TextInputType.phone,
              controller: logic.accountController,
              hintText: logic.isEmailLogin.value ? '请输入电子邮箱' : '请输入手机号码',
              border: null,
              bgColor: AppColor.inputBackground,
              height: 50,
              contentPadding: EdgeInsets.symmetric(horizontal: 6),
              prefixIcon: Padding(padding: AppSpaces.edgeMd, child: Icon(Icons.verified_user_outlined, color: AppColor.primary, size: 20)),
              suffixIcon: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                mainAxisSize: MainAxisSize.min,
                children: [
                  if (logic.accountController.text.isNotEmpty && logic.accountFocusNode.hasFocus)
                    AppGesture(
                      padding: EdgeInsets.symmetric(horizontal: 4),
                      onTap: () {
                        logic.accountController.clear();
                      },
                      child: Image.asset(AppIcon.icClose, width: 20),
                    ),
                ],
              ),
            ),
          ],
        );
      }),
    );
  }

  Widget _buildVerificationCodeInput() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text('验证码', style: TextStyle(color: Get.theme.colorScheme.onSurface, fontSize: 14)),
          SizedBox(height: 8),
          Row(
            children: [
              Expanded(
                child: AppTextField.prefixInput(
                  focusNode: logic.codeFocusNode,
                  keyboardType: TextInputType.number,
                  controller: logic.codeController,
                  hintText: '请输入验证码',
                  border: null,
                  bgColor: AppColor.inputBackground,
                  height: 50,
                  contentPadding: EdgeInsets.symmetric(horizontal: 6),
                  prefixIcon: Padding(padding: AppSpaces.edgeMd, child: Icon(Icons.lock_outline, color: AppColor.primary, size: 20)),
                  suffixIcon: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      if (logic.codeController.text.isNotEmpty && logic.codeFocusNode.hasFocus)
                        AppGesture(
                          padding: EdgeInsets.symmetric(horizontal: 4),
                          onTap: () {
                            logic.codeController.clear();
                          },
                          child: Image.asset(AppIcon.icClose, width: 20),
                        ),
                    ],
                  ),
                ),
              ),
              SizedBox(width: 12),
              Obx(
                () => SizedBox(
                  width: 100,
                  height: 50,
                  child: AppButton.text(
                    text: logic.codeButtonText,
                    onTap: logic.canSendCode.value ? logic.sendVerificationCode : null,
                    enable: logic.canSendCode.value,
                    backgroundColor: logic.canSendCode.value ? AppColor.primary : AppColor.buttonDisabled,
                    disableBackgroundColor: AppColor.buttonDisabled,
                    style: AppStyles.s14w5,
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildPrivacy() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16),
      child: Row(
        children: [
          Obx(
            () => GestureDetector(
              onTap: logic.toggleAgree,
              child: Container(
                width: 20,
                height: 20,
                decoration: BoxDecoration(
                  color: logic.agree.value ? AppColor.primary : Colors.transparent,
                  border: Border.all(color: logic.agree.value ? AppColor.primary : AppColor.border, width: 2),
                  borderRadius: BorderRadius.circular(4),
                ),
                child: logic.agree.value ? Icon(Icons.check, color: AppColor.white, size: 16) : null,
              ),
            ),
          ),
          SizedBox(width: 8),
          Expanded(
            child: RichText(
              text: TextSpan(
                text: LoginIntl.agree.tr,
                style: AppStyles.s14w5.copyWith(color: Get.theme.colorScheme.onSurface.withOpacity(0.6)),
                children: [
                  TextSpan(
                    text: LoginIntl.privacyPolicy.tr,
                    style: AppStyles.s14w5.copyWith(color: Get.theme.colorScheme.primary),
                    recognizer:
                        TapGestureRecognizer()
                          ..onTap = () async {
                            logic.openPrivacyPolicy();
                            // final result = await Get.dialog<bool>(ServiceTermsDialog(), barrierDismissible: false);
                          },
                  ),
                  TextSpan(text: "和", style: AppStyles.s14.copyWith(color: Get.theme.colorScheme.onSurface.withOpacity(0.6))),
                  TextSpan(
                    text: LoginIntl.termsOfService.tr,
                    style: AppStyles.s14w5.copyWith(color: Get.theme.colorScheme.primary),
                    recognizer:
                        TapGestureRecognizer()
                          ..onTap = () async {
                            logic.openTermsOfService();
                            // final result = await Get.dialog<bool>(ServiceTermsDialog(), barrierDismissible: false);
                          },
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildLoginButton() {
    return Container(
      margin: EdgeInsets.only(left: 16, right: 16),
      child: Obx(
        () => AppButton.text(
          text: LoginIntl.login.tr,
          onTap: logic.canSubmit.value ? logic.login : null,
          enable: logic.canSubmit.value,
          backgroundColor: Get.theme.colorScheme.primary,
          disableBackgroundColor: Get.theme.colorScheme.secondary.withOpacity(0.6),
          style: AppStyles.s16w5,
        ),
      ),
    );
  }

  Widget _buildSignUpSection() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Padding(padding: EdgeInsets.symmetric(vertical: 10), child: Text('我还没有账号', style: AppStyles.s14)),
        AppGesture(padding: EdgeInsets.symmetric(horizontal: 4), onTap: logic.navigateToSignUp, child: Image.asset(AppIcon.noAccount, width: 54)),
      ],
    );
  }
}
